package api

import (
	"fmt"
	"net/http"
	"strconv"
	"time"

	"erp/config"
	"erp/logic"
	"erp/model"
	"erp/util"

	"github.com/gin-gonic/gin"
)

func RegisterDeliveryRoutes(r *gin.Engine) {
	s := logic.OrderService{DB: config.DB}

	// 获取所有送货单
	r.GET("/deliveries", func(c *gin.Context) {
		p := util.GetPage(c)
		var list []model.Order
		q := config.DB.Model(&model.Order{}).Where("shipment_no IS NOT NULL AND shipment_no != ''")

		// 按送货单号查询
		if shipmentNo := c.Query("shipment_no"); shipmentNo != "" {
			q = q.Where("shipment_no LIKE ?", "%"+shipmentNo+"%")
		}

		// 按客户查询
		if customer := c.Query("customer"); customer != "" {
			q = q.Where("customer LIKE ?", "%"+customer+"%")
		}

		// 按状态查询
		if status := c.Query("status"); status != "" {
			q = q.Where("status = ?", status)
		}

		// 按日期范围查询
		if startDate := c.Query("start_date"); startDate != "" {
			q = q.Where("delivery_date >= ?", startDate)
		}
		if endDate := c.Query("end_date"); endDate != "" {
			q = q.Where("delivery_date <= ?", endDate)
		}

		var total int64
		q.Count(&total)
		if err := q.Preload("Items").Offset(p.Offset).Limit(p.Limit).Order("delivery_date DESC, id DESC").Find(&list).Error; err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		c.JSON(http.StatusOK, gin.H{"items": list, "total": total, "page": p.Page, "pageSize": p.PageSize})
	})

	// 获取送货单详情
	r.GET("/deliveries/:id", func(c *gin.Context) {
		var order model.Order
		if err := config.DB.Preload("Items").First(&order, c.Param("id")).Error; err != nil {
			c.JSON(http.StatusNotFound, gin.H{"error": "送货单不存在"})
			return
		}
		if order.ShipmentNo == "" {
			c.JSON(http.StatusBadRequest, gin.H{"error": "该订单未生成送货单"})
			return
		}
		c.JSON(http.StatusOK, order)
	})

	// 打印送货单（返回打印格式数据）
	r.GET("/deliveries/:id/print", func(c *gin.Context) {
		id64, _ := strconv.ParseUint(c.Param("id"), 10, 64)
		deliveryNote, err := s.GetDeliveryNote(uint(id64))
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		c.JSON(http.StatusOK, deliveryNote)
	})

	// 批量打印送货单
	r.POST("/deliveries/batch/print", func(c *gin.Context) {
		var req struct {
			OrderIDs []uint `json:"order_ids"`
		}
		if err := c.ShouldBindJSON(&req); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}

		var deliveryNotes []map[string]interface{}
		for _, id := range req.OrderIDs {
			note, err := s.GetDeliveryNote(id)
			if err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("订单 %d: %v", id, err)})
				return
			}
			deliveryNotes = append(deliveryNotes, note)
		}

		c.JSON(http.StatusOK, gin.H{
			"delivery_notes": deliveryNotes,
			"total":          len(deliveryNotes),
			"print_time":     time.Now().Format("2006-01-02 15:04:05"),
		})
	})

	// 获取送货单统计
	r.GET("/deliveries/stats", func(c *gin.Context) {
		stats, err := s.GetDeliveryStats()
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		c.JSON(http.StatusOK, stats)
	})

	// 导出送货单数据（CSV格式）
	r.GET("/deliveries/export", func(c *gin.Context) {
		var list []model.Order
		q := config.DB.Model(&model.Order{}).Where("shipment_no IS NOT NULL AND shipment_no != ''")

		// 应用查询条件
		if startDate := c.Query("start_date"); startDate != "" {
			q = q.Where("delivery_date >= ?", startDate)
		}
		if endDate := c.Query("end_date"); endDate != "" {
			q = q.Where("delivery_date <= ?", endDate)
		}
		if status := c.Query("status"); status != "" {
			q = q.Where("status = ?", status)
		}

		if err := q.Preload("Items").Order("delivery_date DESC").Find(&list).Error; err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}

		// 设置CSV响应头
		c.Header("Content-Type", "text/csv; charset=utf-8")
		c.Header("Content-Disposition", "attachment; filename=deliveries.csv")

		// 写入CSV头部
		c.Writer.Write([]byte("送货单号,客户名称,送货日期,送货地址,联系人,电话,仓库,包装员,发货员,运输方式,总金额,状态\n"))

		// 写入数据
		for _, order := range list {
			line := fmt.Sprintf("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%.2f,%s\n",
				order.ShipmentNo,
				order.Customer,
				order.DeliveryDate,
				order.DeliveryAddress,
				order.DeliveryContact,
				order.DeliveryPhone,
				order.Warehouse,
				order.Packager,
				order.Shipper,
				order.ShippingMethod,
				order.FinalAmount,
				order.Status,
			)
			c.Writer.Write([]byte(line))
		}
	})

	// 重新生成送货单号
	r.PUT("/deliveries/:id/regenerate", func(c *gin.Context) {
		id64, _ := strconv.ParseUint(c.Param("id"), 10, 64)
		if err := s.RegenerateShipmentNo(uint(id64)); err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}
		c.JSON(http.StatusOK, gin.H{"message": "送货单号重新生成成功"})
	})
}
